package com.controller;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.pojo.Dep;
import com.service.DepService;
import com.vo.ResponseBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

@RestController
@CrossOrigin("*")
@RequestMapping({"/api"})
public class DepController {

    @Autowired
    private DepService depService;

    @Autowired
    private HttpServletRequest request;

    @Value("${upload.dir}")
    private String tmp;



    @RequestMapping({"/searchDep"})
    public ResponseBean searchDep(@RequestParam(defaultValue = "1")int page,@RequestParam(defaultValue = "10")int limit,Integer depId,String depName){
        IPage result=depService.searchDep(page,limit,depId,depName);
        return new ResponseBean(0,result.getTotal(),result.getRecords());
    }


    @RequestMapping({"/removeDepById"})
    public ResponseBean removeDepById(String depId){
        boolean f=depService.removeById(depId);
        int code=f ? 200:500;
        return new ResponseBean(code,0,null);
    }

    @RequestMapping({"/addDep"})
    public ResponseBean addDep(Dep dep){
        boolean f= depService.save(dep);
        ResponseBean bean=null;

        int code=f ? 200:500;

        if (code==200){

            String descDir=request.getServletContext().getRealPath("/images");
            File descDirFile=new File(descDir);
            if (descDirFile.exists()==false){
                descDirFile.mkdirs();
            }
            FileUtil.copy(tmp+"/"+dep.getImage(),descDir+"/"+dep.getImage(),true);

        }

        return new ResponseBean(code,0,null);
    }

    @RequestMapping({"/updateDep"})
    public ResponseBean updateDep(Dep dep){

        boolean b = depService.updateById(dep);

        int code= b?200:500;

        if (code==200){
            String descDir=request.getServletContext().getRealPath("/images");
            File descDirFile=new File(descDir);
            if(descDirFile.exists()==false){
                descDirFile.mkdirs();
            }
            FileUtil.copy(tmp+"/"+dep.getImage(),descDir+"/"+dep.getImage(),true);
        }
        return new ResponseBean(code,0,null);
    }

}
